package com.bodacn.keypoint;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static android.content.Context.MODE_PRIVATE;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentM extends Fragment implements View.OnClickListener {
    public static final int msgFocusBarcode = 1001;
    public static final int MSG_DETAIL = 9002;
    public static final int MSG_PROCRESULT=9004;
    public static final int MSG_SUBMIT=9005;
    public static final int MSG_ERRMSG=9999;

    public static String TAG= FragmentM.class.getName();
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    //全局变量
    Toast curToast;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID;
    Button btn_find;
    ImageButton btn_editBarcode;
    ListView detailListView;
    TextView txt_HintInfo,txt_OrderNo,txt_StyleNo,txt_PO,txt_Color,txt_Size,txt_SonPertain,txt_Barcode,txt_TotalNum, txt_ScanNum,txt_OwenNum;
    Button btn_Submit,btn_Clear,btn_Query;
    CheckBox chk_Speech;
    EditText edt_barcode;
    CheckBox check_AutoSave;
    JSONArray resultJSON, detailJSON,procRstJSON;
    String BatchID;
    private FragmentMCallBack mFragmentMCallBack;
    /*定义一个业务接口,主程序负责实现，所以需在主程序implements中加上这个接口的引用>>>>>切记<<<<<<
    该Fragment所在Activity需要实现该接口
  该Fragment将通过此接口与它所在的Activity交互*/
    public interface FragmentMCallBack {
        // 里面传个值@param Map<String,Object>适应多种类型;
        void FragmentMWorkAndTransParams(Map<String, Object> Params);
    }
    private ProgressDialog waitDialog = null;
    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity = (Activity) context;
        if (!(activity instanceof FragmentMCallBack)) {
            throw new IllegalStateException("MaMinActivity必须实现FragmentMCallBack接口");
        }
        mFragmentMCallBack=(FragmentMCallBack) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mFragmentMCallBack=null;
    }

    //消息回调
    public void ToSpeech(String paramText){
        if (chk_Speech.isChecked()==false) return;
        //传消息给主界面;
        System.out.println("ToSpeech-------------------准备回调");
        if (mFragmentMCallBack!=null)
        {
            System.out.println("ToSpeech-------------------回调过程");
            fragmentParams.clear();
            fragmentParams.put("ParamComm","Speech");//命令;
            fragmentParams.put("Text",paramText);//命令;
            mFragmentMCallBack.FragmentMWorkAndTransParams(fragmentParams);
        } else Log.d("msg","mFragmentECallBack-----------空的咋办");
    }
    public FragmentM() {
        // Required empty public constructor
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerM(new MainActivity.OnTransParamsListenerM() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d(TAG,"LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir=mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            CPUID=mParams.get("CPUID").toString();
                            Log.d(TAG,"LoginParam------------------>2");
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }




    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    //设置焦点到扫描输入框
    private void setEditBarcodeFocus()
    {
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        if (edt_barcode!=null) {
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
            hideIM(getView());
            hideBottomUIMenu();
        }
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_m, container, false);
        InitView(root);
        System.out.println(TAG+"_onCreateView");
        return root;
    }

    //初始化;
    public void InitView(View view){
        detailListView=(ListView) view.findViewById(R.id.detailListView);
        detailListView.setFocusable(false);
        detailListView.setFocusableInTouchMode(false);
        detailListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if ((txt_TotalNum.getText()==null)||Integer.valueOf(txt_TotalNum.getText().toString())==0){
                    fillFormtext(i);
                    BatchID= UUID.randomUUID().toString();
                    txt_HintInfo.setText("请开始扫描!");
                    ToSpeech(txt_HintInfo.getText().toString());
                }
                else {
                    txt_HintInfo.setText("已有扫描不能切换商品码,请先提交或清除!");
                    ToSpeech(txt_HintInfo.getText().toString());
                    curToast.setText("已有扫描不能切换商品码,请先提交或清除!");
                    curToast.show();
                }

            }
        });
        btn_Submit=view.findViewById(R.id.btn_Submit);
        btn_Submit.setOnClickListener(this);
        btn_Clear=view.findViewById(R.id.btn_Clear);
        btn_Clear.setOnClickListener(this);
        btn_find=view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_Query=view.findViewById(R.id.btn_Query);
        btn_Query.setOnClickListener(this);
        btn_editBarcode=view.findViewById(R.id.btn_editBarcode);
        btn_editBarcode.setOnClickListener(this);
        btn_editBarcode.setFocusable(false);
        btn_editBarcode.setFocusableInTouchMode(false);
        check_AutoSave=view.findViewById(R.id.check_AutoSave);
        check_AutoSave.setOnClickListener(this);
        //界面Edit;
        edt_barcode=view.findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        playRingtone();
                        btn_find.performClick();
                    }

                }
                return false;
            }
        });
        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();
        txt_HintInfo=view.findViewById(R.id.txt_HintInfo);
        txt_OrderNo=view.findViewById(R.id.txt_OrderNo);
        txt_StyleNo=view.findViewById(R.id.txt_StyleNo);
        txt_PO=view.findViewById(R.id.txt_PO);
        txt_Color=view.findViewById(R.id.txt_Color);
        txt_SonPertain=view.findViewById(R.id.txt_SonPertain);
        txt_Size=view.findViewById(R.id.txt_Size);
        txt_Barcode=view.findViewById(R.id.txt_Barcode);
        txt_TotalNum=view.findViewById(R.id.txt_TotalNum);
        txt_ScanNum =view.findViewById(R.id.txt_ScanNum);
        txt_OwenNum=view.findViewById(R.id.txt_OwenNum);
        chk_Speech=view.findViewById(R.id.chk_Speech);

        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);
        //提示框pd=new ProgressDialog(this);
        waitDialog = new ProgressDialog(getActivity());
        waitDialog.setTitle(getString(R.string.SystemHint));
    }

    /**
     * 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理 * * @param directory
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }
    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.btn_find:
                //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                //隐藏键盘
                System.out.println("0.1");
                hideIM(v);
                System.out.println("0.2");
                if (edt_barcode.getText()==null) {
                    curToast.setText(getString(R.string.PleaseInputBarcode));
                    curToast.show();
                } else {
                    if (txt_Barcode.getText()!= null) {
                        if (edt_barcode.getText().toString().equals(txt_Barcode.getText().toString())) {
                            if (txt_TotalNum.getText() == null) txt_TotalNum.setText("0");
                            else {
                                if ((txt_OwenNum.getText() != null) && (isNumeric(txt_TotalNum.getText().toString()) == true)) {
                                    //增加一,如果超过剩余数，提醒扫描完成,不让进;
                                    if (Integer.valueOf(txt_OwenNum.getText().toString()) > Integer.valueOf(txt_TotalNum.getText().toString())) {
                                        txt_TotalNum.setText(String.valueOf(Integer.valueOf(txt_TotalNum.getText().toString()) + 1));
                                        txt_HintInfo.setText("扫描成功!");
                                        ToSpeech(txt_TotalNum.getText().toString());
                                        if (check_AutoSave.isChecked()) btn_Submit.performClick();
                                    } else {
                                        txt_HintInfo.setText("扫描已结束,禁止扫描!");
                                        ToSpeech(txt_HintInfo.getText().toString());
                                    }
                                }
                            }
                        } else {
                            if (txt_Barcode.getText().length()==0)  refreshDetailData(edt_barcode.getText().toString());
                            else {
                                txt_HintInfo.setText("条码不符,禁止扫描!");
                                ToSpeech(txt_HintInfo.getText().toString());
                            }
                        }
                    } else refreshDetailData(edt_barcode.getText().toString());
                }
                //未有焦点
                if (edt_barcode.isFocused()==false){
                    //发消息置焦点
                    Message msg =new Message();
                    msg.what = msgFocusBarcode;
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                } else edt_barcode.selectAll();
                break;
            case R.id.check_AutoSave:
                //读取配置文件-设置语言String STORE_NAME = "";
                SharedPreferences settings = getActivity().getSharedPreferences("Settings", MODE_PRIVATE);
                SharedPreferences.Editor set_editor=settings.edit();
                set_editor.putBoolean("ScanSave",check_AutoSave.isChecked());
                set_editor.commit();
                break;
            case R.id.chk_Speech:
                //读取配置文件-设置语言String STORE_NAME = "";
                SharedPreferences settings1 = getActivity().getSharedPreferences("Settings", MODE_PRIVATE);
                SharedPreferences.Editor set_editor1=settings1.edit();
                set_editor1.putBoolean("Speech",chk_Speech.isChecked());
                set_editor1.commit();
                break;
            case R.id.btn_Query:
                Intent intentQueryActivity=new Intent(getContext(),QueryActivity.class);
                Bundle paramBundle = new Bundle();
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("ServiceUrl",curServiceUrl);
                paramBundle.putString("ServiceDir",curServiceDir);
                paramBundle.putString("CPUID",CPUID);
                paramBundle.putString("QueryTitle", "验针扫描查询");
                paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                intentQueryActivity.putExtras(paramBundle);
                startActivity(intentQueryActivity);
                break;
            case R.id.btn_editBarcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;
            case R.id.btn_Clear:
                clearFormText();
                BatchID=UUID.randomUUID().toString();
                break;
            case R.id.btn_Submit:
                if ((txt_TotalNum.getText()!=null)&&(txt_Barcode.getText()!=null))
                {
                    if ((txt_TotalNum.getText().length()>0)&(txt_Barcode.getText().length()>0)){
                        //如果件数大于0,则提交
                        if (Integer.valueOf(txt_TotalNum.getText().toString())>0){
                            SubmitScan();
                        } else{
                            txt_HintInfo.setText("件数为零,请先扫描!");
                            ToSpeech(txt_HintInfo.getText().toString());
                        }
                    } else{
                        txt_HintInfo.setText("件数为零或条码为空,不能保存!");
                        ToSpeech(txt_HintInfo.getText().toString());
                    }
                }
                break;
            default:
                break;
        }
    }

    //保存明细;
    private void SubmitScan() {
        //执行SQL过程
        String SqlComm="Exec NeedleScanBarcode @OPERTYPE='SUBMIT',@ScanNum='"+txt_TotalNum.getText().toString()
                +"',@BatchID='"+BatchID
                +"',@OrderNo='"+txt_OrderNo.getText().toString()
                +"',@StyleNo='"+txt_StyleNo.getText().toString()
                +"',@PO='"+txt_PO.getText().toString()
                +"',@Color='"+txt_Color.getText().toString()
                +"',@Size='"+txt_Size.getText().toString()
                +"',@SonAttrib='"+txt_SonPertain.getText().toString()
                +"',@SelBarcode='"+txt_Barcode.getText().toString()
                +"',@LoginUserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //刷新今日扫描明细;
    private void refreshDetailData(String paramBarcode)
    {
        try {
            detailJSON=new JSONArray("[]");
            //显示到orderListGrid中;
            final DetailListAdapter detailListAdapter=new DetailListAdapter(getActivity());
            detailListView.setAdapter(detailListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec NeedleBarcode @Barcode='" + paramBarcode  + "',@OPERTYPE='DETAIL',@UserNo='"+curLoginUserNo+ "',@CPUID='" + CPUID +"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }

    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                //任意消息来均置焦点
                if (edt_barcode.isFocused()==false) setEditBarcodeFocus();
                else edt_barcode.selectAll();
                System.out.println("收到的消息是："+msg.what);
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_ERRMSG:
                        //提示提交完成，需确认;
                        Bundle bundle1=msg.getData();
                        String resultMsg=bundle1.getString("Hint");
                        // 创建对话框
                        AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                                .setTitle("系统提示").setMessage(resultMsg)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).create();
                        alertDialog.show(); // 显示对话框
                        break;
                    case MSG_DETAIL:
                        if (detailJSON.length()==1)  fillFormtext(0);
                        else{
                            //提示请选择需扫描的商品码;
                            txt_HintInfo.setText("请选择要扫描的商品码!");
                            ToSpeech(txt_HintInfo.getText().toString());
                        }
                        //显示预排单;
                        final DetailListAdapter detailListAdapter = new DetailListAdapter(getActivity());
                        detailListView.setAdapter(detailListAdapter);
                        break;
                    case MSG_SUBMIT:
                        try {
                            if (resultJSON.getJSONObject(0).has("OrderNo")==true) txt_OrderNo.setText(resultJSON.getJSONObject(0).getString("OrderNo"));
                            if (resultJSON.getJSONObject(0).has("StyleNo")==true) txt_StyleNo.setText(resultJSON.getJSONObject(0).getString("StyleNo"));
                            if (resultJSON.getJSONObject(0).has("PO")==true) txt_PO.setText(resultJSON.getJSONObject(0).getString("PO"));
                            if (resultJSON.getJSONObject(0).has("Color")==true) txt_Color.setText(resultJSON.getJSONObject(0).getString("Color"));
                            if (resultJSON.getJSONObject(0).has("Size")==true) txt_Size.setText(resultJSON.getJSONObject(0).getString("Size"));
                            if (resultJSON.getJSONObject(0).has("SonPertain")==true) txt_SonPertain.setText(resultJSON.getJSONObject(0).getString("SonPertain"));
                            if (resultJSON.getJSONObject(0).has("Barcode")==true) txt_Barcode.setText(resultJSON.getJSONObject(0).getString("Barcode"));
                            if (resultJSON.getJSONObject(0).has("ScanNum")==true) txt_ScanNum.setText(resultJSON.getJSONObject(0).getString("ScanNum"));
                            if (resultJSON.getJSONObject(0).has("OwenNum")==true) txt_OwenNum.setText(resultJSON.getJSONObject(0).getString("OwenNum"));
                            if (resultJSON.getJSONObject(0).has("TotalNum")==true) txt_TotalNum.setText(resultJSON.getJSONObject(0).getString("TotalNum"));
                            else txt_TotalNum.setText("0");
                            if (resultJSON.getJSONObject(0).has("ResultInfo")==true) {
                                txt_HintInfo.setText(resultJSON.getJSONObject(0).getString("ResultInfo"));
                                ToSpeech(txt_HintInfo.getText().toString());
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        break;
                    case MSG_PROCRESULT:
                        resultMsg="";
                        try {
                            resultMsg = procRstJSON.optJSONObject(0).getString("PROCRESULT");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        //提示提交完成，需确认;
                        // 创建对话框
                        AlertDialog alertDialog1 = new AlertDialog.Builder(getActivity())
                                .setTitle(getString(R.string.SystemHint)).setMessage(resultMsg)
                                .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        hideBottomUIMenu();
                                    }
                                }).create();
                        alertDialog1.show(); // 显示对话框
                        break;
                    default:
                        break;
                }
            }
        }
    };


    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OPERTYPE") == true) {
                            System.out.println("OPERTYPE:" + jsonArray.optJSONObject(0).getString("OPERTYPE"));
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("SUBMIT")) {
                                resultJSON = jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_SUBMIT;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }

                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("DETAIL"))
                            {
                                detailJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_DETAIL;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);

                            }

                        }
                        if (jsonArray.optJSONObject(0).has("PROCRESULT") == true) {
                            procRstJSON=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_PROCRESULT;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            Message message = new Message();
                            message.what = MSG_ERRMSG;
                            Bundle bundle = new Bundle();
                            bundle.putString("Hint", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            message.setData(bundle);
                            fragmentHandler.sendMessage(message);
                        }

                    } else {
                        Message message = new Message();
                        message.what = MSG_ERRMSG;
                        Bundle bundle = new Bundle();
                        bundle.putString("Hint", "未返回任何数据!");
                        fragmentHandler.removeMessages(message.what);
                        fragmentHandler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = MSG_ERRMSG;
                    Bundle bundle = new Bundle();
                    bundle.putString("Hint", e.getMessage().toString());
                    message.setData(bundle);
                    fragmentHandler.sendMessage(message);
                }


            }

        };
        new Thread(run).start();
    }



    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_m_item, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(38)));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                if (detailJSON.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = detailJSON.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                TextView tv = (TextView) convertView.findViewById(R.id.txt_item_OrderNo);// 显示文字
                if (detailJSON.optJSONObject(position).has("OrderNo")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("OrderNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_StyleNo);// 显示文字
                if (detailJSON.optJSONObject(position).has("StyleNo")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("StyleNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_PO);// 显示文字
                if (detailJSON.optJSONObject(position).has("PO")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("PO").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_Color);// 显示文字
                if (detailJSON.optJSONObject(position).has("Color")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("Color").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_Size);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("Size").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_SonPertain);// 显示文字
                if (detailJSON.optJSONObject(position).has("SonPertain")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("SonPertain").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_Barcode);// 显示文字
                if (detailJSON.optJSONObject(position).has("Barcode")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("Barcode").toString());
                tv.setTextColor(color);

                tv = (TextView) convertView.findViewById(R.id.txt_item_TotalNum);// 显示文字
                if (detailJSON.optJSONObject(position).has("TotalNum")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("TotalNum").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_ScanNum);// 显示文字
                if (detailJSON.optJSONObject(position).has("ScanNum")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("ScanNum").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_OwenNum);// 显示文字
                if (detailJSON.optJSONObject(position).has("OwenNum")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("OwenNum").toString());
                tv.setTextColor(color);

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }
    }

    //清除界面显示内容
    private void clearFormText(){
        txt_HintInfo.setText("");
        txt_OrderNo.setText("");
        txt_StyleNo.setText("");
        txt_PO.setText("");
        txt_Color.setText("");
        txt_Size.setText("");
        txt_SonPertain.setText("");
        txt_Barcode.setText("");
        txt_TotalNum.setText("0");
        txt_ScanNum.setText("");
        txt_OwenNum.setText("");


    }

    //填充界面显示内容;
    private void fillFormtext(int index){
        if (detailJSON.length()>index)
        {
            try {
                System.out.println(1);
                if (detailJSON.getJSONObject(index).has("OrderNo")==true) txt_OrderNo.setText(detailJSON.getJSONObject(index).getString("OrderNo"));
                if (detailJSON.getJSONObject(index).has("StyleNo")==true) txt_StyleNo.setText(detailJSON.getJSONObject(index).getString("StyleNo"));
                if (detailJSON.getJSONObject(index).has("PO")==true) txt_PO.setText(detailJSON.getJSONObject(index).getString("PO"));
                if (detailJSON.getJSONObject(index).has("Color")==true) txt_Color.setText(detailJSON.getJSONObject(index).getString("Color"));
                if (detailJSON.getJSONObject(index).has("Size")==true) txt_Size.setText(detailJSON.getJSONObject(index).getString("Size"));
                if (detailJSON.getJSONObject(index).has("SonPertain")==true) txt_SonPertain.setText(detailJSON.getJSONObject(index).getString("SonPertain"));
                if (detailJSON.getJSONObject(index).has("Barcode")==true) txt_Barcode.setText(detailJSON.getJSONObject(index).getString("Barcode"));
                if (detailJSON.getJSONObject(index).has("ScanNum")==true) txt_ScanNum.setText(detailJSON.getJSONObject(index).getString("ScanNum"));
                if (detailJSON.getJSONObject(index).has("OwenNum")==true) txt_OwenNum.setText(detailJSON.getJSONObject(index).getString("OwenNum"));
                txt_TotalNum.setText("0");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden==false){
            //读配置文件
            System.out.println("Read Set ScanSave");
            SharedPreferences settings = getActivity().getSharedPreferences("Settings", MODE_PRIVATE);
            check_AutoSave.setChecked(settings.getBoolean("ScanSave",true));
            chk_Speech.setChecked(settings.getBoolean("Speech",true));
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        setEditBarcodeFocus();
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }
}